package com.xywh.dakaqiandao.mvp.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.baidu.idl.face.platform.FaceConfig;
import com.baidu.idl.face.platform.FaceEnvironment;
import com.baidu.idl.face.platform.FaceSDKManager;
import com.baidu.idl.face.platform.LivenessTypeEnum;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.CoordUtil;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.inner.Point;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.xywh.dakaqiandao.R;
import com.xywh.dakaqiandao.app.ChuRuKuApplication;
import com.xywh.dakaqiandao.di.component.DaggerQianDaoComponent;
import com.xywh.dakaqiandao.di.module.QianDaoModule;
import com.xywh.dakaqiandao.face.Config;
import com.xywh.dakaqiandao.face.FaceLivenessExpActivity;
import com.xywh.dakaqiandao.mvp.contract.QianDaoContract;
import com.xywh.dakaqiandao.mvp.presenter.QianDaoPresenter;
import com.xywh.dakaqiandao.mvp.ui.entity.Faceverify;
import com.xywh.dakaqiandao.mvp.ui.entity.GetAuth;
import com.xywh.dakaqiandao.mvp.ui.entity.GetPersonalCoor;
import com.xywh.dakaqiandao.mvp.ui.entity.QianDao;
import com.xywh.dakaqiandao.mvp.ui.util.DistanceUtil;

import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.armscomponent.commonres.utils.BottomDialogUtil;
import me.jessyan.armscomponent.commonres.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import me.jessyan.armscomponent.commonsdk.utils.Utils;
import okhttp3.RequestBody;
import pub.devrel.easypermissions.EasyPermissions;

import static com.jess.arms.base.BaseConstants.BASE_URL;
import static com.jess.arms.base.BaseConstants.NAME_SPACE;
import static com.jess.arms.base.BaseConstants.NICKNAME;
import static com.jess.arms.utils.Preconditions.checkNotNull;
import static com.xywh.dakaqiandao.mvp.ui.util.GpsUtil.GPS_REQUEST_CODE;

//import com.hss01248.frescopicker.FrescoIniter;
//import com.hss01248.photoouter.PhotoCallback;
//import com.hss01248.photoouter.PhotoUtil;

@Route(path = RouterHub.ACTIVITY_QIAN_DAO)
public class QianDaoActivity extends BaseActivity<QianDaoPresenter> implements QianDaoContract.View, SensorEventListener, View.OnClickListener, EasyPermissions.PermissionCallbacks {
    public TextView mTime_tv;
    @BindView(R.id.btnRight)
    ImageView mBtnRight;
    @BindView(R.id.tv_dang_qian_jing_wei_du)
    TextView tvDangQianJingWeiDu;
    /**
     * 规定到达距离范围距离
     */
    private int DISTANCE = 800;
    private MapView mMapView;
    private TextView mDistance_tv;
    private ImageView imgTouXiang;
    private ImageView img_ding_wei;
    private RelativeLayout commit_bt;
    private BaiduMap mBaiduMap;
    private SensorManager mSensorManager;//方向传感器
    private LatLng mDestinationPoint;//目的地坐标点
    private LocationClient client;//定位监听
    private LocationClientOption mOption;//定位属性
    private MyLocationData locData;//定位坐标
    private InfoWindow mInfoWindow;//地图文字位置提醒
    private double mCurrentLat = 0.0;
    private double mCurrentLon = 0.0;
    private int mCurrentDirection = 0;
    private double mDistance = 0;
    private LatLng mCenterPos;
    private float mZoomScale = 0; //比例
    private Double lastX = 0.0;
    private String[] permissionsLocation = {Manifest.permission.ACCESS_COARSE_LOCATION};
    /**
     * 设置系统时间
     */
    private Runnable run = new Runnable() {
        @Override
        public void run() {
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");// HH:mm:ss
//            Date date = new Date(System.currentTimeMillis());//获取当前时间
//            mTime_tv.setText(simpleDateFormat.format(date)); //更新时间
//            mHandler.postDelayed(run, 1000);
        }
    };
    /**
     * 构造广播监听类，监听 SDK key 验证以及网络异常广播
     */
    private SDKReceiver mReceiver;
    private String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
    private BottomDialogUtil mBottomDialogUtilShare;
    private String imgStr = "";
    private String mCity = "";
    private Toolbar toolbar;
    private List<GetPersonalCoor> getPersonalCoors;
    private int mZuiJinIndex = 0;
    private int mRegionId = 0;
    private boolean isCanDaKa = false;
    /**
     * 处理连续定位的地图UI变化
     */
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);


            BDLocation location = (BDLocation) msg.obj;
            LatLng LocationPoint = new LatLng(location.getLatitude(), location.getLongitude());

//            if (getPersonalCoors != null && getPersonalCoors.size() > 0) {
//
//                //打卡范围
////            mDestinationPoint = new LatLng(location.getLatitude() * 1.0001, location.getLongitude() * 1.0001);//假设公司坐标
//                mDestinationPoint = new LatLng(Double.parseDouble(getPersonalCoors.get(mZuiJinIndex).getCoordinate().split(",")[1]), Double.parseDouble(getPersonalCoors.get(mZuiJinIndex).getCoordinate().split(",")[0]));//假设公司坐标
////            mDestinationPoint = new LatLng(39.916527 * 1.0001, 116.397128 * 1.0001);//假设公司坐标
//                setCircleOptions();
//                //计算两点距离,单位：米
//                mDistance = DistanceUtil.getDistance(mDestinationPoint, LocationPoint);
//                if (mDistance <= DISTANCE) {
//                    //显示文字
//                    setTextOption(mDestinationPoint, "您已在签到范围内", "#7ED321");
//                    showMessage("您已在签到范围内");
//                    //目的地图标
//                    setMarkerOptions(mDestinationPoint, R.mipmap.arrive_icon);
//                    //按钮颜色
//                    commit_bt.setBackgroundDrawable(getResources().getDrawable(R.drawable.restaurant_btbg_yellow));
//                    mBaiduMap.setMyLocationEnabled(false);
//                } else {
//                    setTextOption(LocationPoint, "您不在签到范围之内", "#FF6C6C");
//                    showMessage("您不在签到范围之内");
//
//                    setMarkerOptions(mDestinationPoint, R.drawable.restaurant_icon);
//                    commit_bt.setBackgroundDrawable(getResources().getDrawable(R.drawable.restaurant_btbg_gray));
//                    mBaiduMap.setMyLocationEnabled(true);
//                }
//            }

            try {
                tvDangQianJingWeiDu.setText("经度：" + mCurrentLon + "     纬度：" + mCurrentLat);
            } catch (Exception e) {
                e.printStackTrace();
            }

            mBaiduMap.setMyLocationEnabled(true);
//            mDistance_tv.setText("距离目的地：" + mDistance + "米");
            //缩放地图
            setMapZoomScale(LocationPoint);
        }
    };
    /***
     * 接收定位结果消息，并显示在地图上
     */
    private BDAbstractLocationListener BDAblistener = new BDAbstractLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //定位方向
            mCurrentLat = location.getLatitude();
            mCurrentLon = location.getLongitude();
            mCity = location.getCity();
            mDistance_tv.setText("当前地址：" + location.getAddrStr());
            //骑手定位
            locData = new MyLocationData.Builder()
                    .direction(mCurrentDirection).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
                    .fromResource(R.drawable.icon_ding_wei_red);
            mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                    MyLocationConfiguration.LocationMode.NORMAL, true, mCurrentMarker));
            //更改UI
            Message message = new Message();
            message.obj = location;
            mHandler.sendMessage(message);


            getPersonalCoor();
        }
    };

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerQianDaoComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .qianDaoModule(new QianDaoModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        if (getLocationPermission()) {
            SDKInitializer.initialize(getApplicationContext());//百度地图
            // 注册 SDK 广播监听者
            RegisterBroadcast();
        }
        initLib();
        return R.layout.activity_map; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    private boolean getLocationPermission() {
        if (EasyPermissions.hasPermissions(this, permissionsLocation)) {

            return true;
        } else {

            EasyPermissions.requestPermissions(this, "需要获取定位权限", 104, permissionsLocation);
            return false;
        }

    }

    protected void RegisterBroadcast() {
        IntentFilter iFilter = new IntentFilter();
        iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK);
        iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR);
        iFilter.addAction(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR);
        mReceiver = new SDKReceiver();
        registerReceiver(mReceiver, iFilter);
    }

    /**
     * 初始化SDK
     */
    private void initLib() {
        // 为了android和ios 区分授权，appId=appname_face_android ,其中appname为申请sdk时的应用名
        // 应用上下文
        // 申请License取得的APPID
        // assets目录下License文件名
        FaceSDKManager.getInstance().initialize(this, Config.licenseID, Config.licenseFileName);
        // setFaceConfig();
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

//        Toolbar toolbar = ToolbarUtils.initToolbarTitleNoBack(this, getString(R.string.activity_qian_dao));
        TextView tvTitle = findViewById(me.jessyan.armscomponent.commonres.R.id.title);
        toolbar = findViewById(me.jessyan.armscomponent.commonres.R.id.toolbar);

        tvTitle.setText(getString(R.string.activity_qian_dao) + "(" + mSharedPreferencesHelper.getString(NICKNAME) + ")");
//        getQianDaoData();
//        PhotoUtil.init(this, new FrescoIniter());

        initBaiduMap();     //1、初始化地图

        getLocationClientOption();//2、定位开启

        mHandler.post(run);//设置系统时间

        mDistance_tv = findViewById(R.id.distance_tv);
        imgTouXiang = findViewById(R.id.img_tou_xiang);
        img_ding_wei = findViewById(R.id.img_ding_wei);
        mTime_tv = findViewById(R.id.arriver_timetv);
        commit_bt = findViewById(R.id.arriver_bt);
        commit_bt.setOnClickListener(this);
        //结果为“0”是上午 结果为“1”是下午
        GregorianCalendar ca = new GregorianCalendar();
        if (ca.get(GregorianCalendar.AM_PM) == 0) {
            mTime_tv.setText("8:30:00");
        } else {
            mTime_tv.setText("17:30:00");
        }

        mBtnRight.setImageDrawable(getResources().getDrawable(R.drawable.icon_setting));
        mBtnRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                toSettingPage();
//                Utils.navigation(QianDaoActivity.this, RouterHub.ACTIVITY_DI_QU_SHE_ZHI);
                Utils.navigation(QianDaoActivity.this, RouterHub.ACTIVITY_PERSON);
            }
        });
        img_ding_wei.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBaiduMap.setMyLocationEnabled(true);
                client.start();
            }
        });
        canChange();
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                LogUtils.debugInfo("AuthService.getAuth()===" + AuthService.getAuth());
//            }
//        }).start();
//        GpsUtil.checkGpsIsOpen(this);

    }

    /**
     * 初始化地图
     */
    private void initBaiduMap() {
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);//获取传感器管理服务
        mMapView = findViewById(R.id.mapview);
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mBaiduMap.setMyLocationEnabled(true);
//        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().zoom(5).build()));

    }

    /***
     * 定位选项设置
     * @return
     */
    public void getLocationClientOption() {
        mOption = new LocationClientOption();
        mOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        mOption.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系，如果配合百度地图使用，建议设置为bd09ll;
        mOption.setScanSpan(1000 * 60 * 1);//可选，默认0，即仅定位一次，设置发起连续定位请求的间隔需要大于等于1000ms才是有效的
        mOption.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        mOption.setIsNeedLocationDescribe(true);//可选，设置是否需要地址描述
        mOption.setNeedDeviceDirect(true);//可选，设置是否需要设备方向结果
        mOption.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        mOption.setIgnoreKillProcess(true);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        mOption.setIsNeedLocationDescribe(false);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        mOption.setIsNeedLocationPoiList(false);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        mOption.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        mOption.setOpenGps(true);//可选，默认false，设置是否开启Gps定位
        mOption.setIsNeedAltitude(false);//可选，默认false，设置定位时是否需要海拔信息，默认不需要，除基础定位版本都可用
        mOption.setPriority(LocationClientOption.GpsOnly);
        client = new LocationClient(this);
        client.setLocOption(mOption);
        client.registerLocationListener(BDAblistener);
        client.start();
    }

    /**
     * //地区经纬度设置是否可用(0:不可用 1:可用)
     */
    private void canChange() {

//        showLoading();

        String methodName = "canChange";

        SoapUtil soapUtil = SoapUtil.getInstance(this);
        soapUtil.setDotNet(true);
        SoapParams params = new SoapParams();


        /**
         * 请求
         */
        soapUtil.callEntry(BASE_URL, NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty("canChangeResult").toString();
                if (result != null && result.equals("1")) {
                    toolbar.setNavigationIcon(R.drawable.icon_ding_wei);
                    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Utils.navigation(getContext(), RouterHub.ACTIVITY_SOU_JI_JING_WEI_DU);

                        }
                    });
                } else {
                    toolbar.setNavigationIcon(null);
                    toolbar.setNavigationOnClickListener(null);
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());


    }

    private void startItemActivity(Class itemClass) {
        setFaceConfig();
        startActivity(new Intent(this, itemClass));
    }

    private void setFaceConfig() {
        FaceConfig config = FaceSDKManager.getInstance().getFaceConfig();
        // SDK初始化已经设置完默认参数（推荐参数），您也根据实际需求进行数值调整
        ChuRuKuApplication.livenessList.clear();
        if (!ChuRuKuApplication.livenessList.contains(LivenessTypeEnum.Eye)) {
            ChuRuKuApplication.livenessList.add(LivenessTypeEnum.Eye);
        }
        config.setLivenessTypeList(ChuRuKuApplication.livenessList);
        config.setLivenessRandom(ChuRuKuApplication.isLivenessRandom);
        config.setBlurnessValue(FaceEnvironment.VALUE_BLURNESS);
        config.setBrightnessValue(FaceEnvironment.VALUE_BRIGHTNESS);
        config.setCropFaceValue(FaceEnvironment.VALUE_CROP_FACE_SIZE);
        config.setHeadPitchValue(FaceEnvironment.VALUE_HEAD_PITCH);
        config.setHeadRollValue(FaceEnvironment.VALUE_HEAD_ROLL);
        config.setHeadYawValue(FaceEnvironment.VALUE_HEAD_YAW);
        config.setMinFaceSize(FaceEnvironment.VALUE_MIN_FACE_SIZE);
        config.setNotFaceValue(FaceEnvironment.VALUE_NOT_FACE_THRESHOLD);
        config.setOcclusionValue(FaceEnvironment.VALUE_OCCLUSION);
        config.setCheckFaceQuality(true);
        config.setFaceDecodeNumberOfThreads(2);

        FaceSDKManager.getInstance().setFaceConfig(config);
    }

    @OnClick(R.id.tv_ding_wei)
    void onChongXinDingWei() {
//        if (GpsUtil.checkGpsIsOpen(this)) {
        showMessage("定位中...");
        client.restart();

        getPersonalCoor();
//        }
    }

    //获取个人已注册地区的经纬度
    private void getPersonalCoor() {

//        showLoading();

        String methodName = "getPersonalCoor";

        SoapUtil soapUtil = SoapUtil.getInstance(this);
        soapUtil.setDotNet(true);
        SoapParams params = new SoapParams();
        params.put("identityCardNo", mSharedPreferencesHelper.getString(BaseConstants.USERNAME));


        /**
         * 请求
         */
        soapUtil.call(BASE_URL, NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty("getPersonalCoorResult").toString();
                if (!TextUtils.isEmpty(result)) {

                    try {
                        getPersonalCoors = new Gson().fromJson(result, new TypeToken<List<GetPersonalCoor>>() {
                        }.getType());
                        if (getPersonalCoors != null && getPersonalCoors.size() > 0) {

                            List<Double> distances = new ArrayList<>();

                            double mZuiJin = 0;

                            for (int i = 0; i < getPersonalCoors.size(); i++) {

                                String[] latLngs = getPersonalCoors.get(i).getCoordinate().split(",");
                                LatLng LocationPoint = new LatLng(mCurrentLat, mCurrentLon);
                                //打卡范围
                                LatLng mDestinationPoint = new LatLng(Double.parseDouble(latLngs[1]), Double.parseDouble(latLngs[0]));//假设公司坐标

                                //计算两点距离,单位：米
                                double mDistance = DistanceUtil.getDistance(mDestinationPoint, LocationPoint);

                                if (i == 0) {
                                    mZuiJin = mDistance;
                                    mZuiJinIndex = 0;
                                    mRegionId = getPersonalCoors.get(0).getRegionId();
                                }
                                LogUtils.debugEInfo("mDistance==" + mDistance);
                                if (mZuiJin > mDistance) {
                                    mZuiJin = mDistance;
                                    mZuiJinIndex = i;
                                    mRegionId = getPersonalCoors.get(i).getRegionId();

                                }

                            }
                            LogUtils.debugEInfo("mZuiJinIndex==" + mZuiJinIndex);
                            LogUtils.debugEInfo("mZuiJinDistance==" + mZuiJin);


                            if (getPersonalCoors != null && getPersonalCoors.size() > 0) {

                                //打卡范围
//            mDestinationPoint = new LatLng(location.getLatitude() * 1.0001, location.getLongitude() * 1.0001);//假设公司坐标
                                mDestinationPoint = new LatLng(Double.parseDouble(getPersonalCoors.get(mZuiJinIndex).getCoordinate().split(",")[1]), Double.parseDouble(getPersonalCoors.get(mZuiJinIndex).getCoordinate().split(",")[0]));//假设公司坐标
//            mDestinationPoint = new LatLng(39.916527 * 1.0001, 116.397128 * 1.0001);//假设公司坐标
                                setCircleOptions();
                                //计算两点距离,单位：米
                                LatLng LocationPoint = new LatLng(mCurrentLat, mCurrentLon);

                                mDistance = DistanceUtil.getDistance(mDestinationPoint, LocationPoint);
                                if (mDistance <= DISTANCE) {
                                    isCanDaKa = true;
                                    //显示文字
                                    setTextOption(mDestinationPoint, "您已在签到范围内,距离打卡地点" + String.format("%.2f", mZuiJin) + "米", "#7ED321");
                                    showMessage("您已在签到范围内,距离打卡地点" + String.format("%.2f", mZuiJin) + "米");
                                    //目的地图标
                                    setMarkerOptions(LocationPoint, R.drawable.icon_ding_wei_red);
                                    setMarkerOptions(mDestinationPoint, R.mipmap.arrive_icon);
                                    //按钮颜色
                                    commit_bt.setBackgroundDrawable(getResources().getDrawable(R.drawable.restaurant_btbg_yellow));
                                    mBaiduMap.setMyLocationEnabled(false);
                                } else {
                                    isCanDaKa = false;
                                    setTextOption(LocationPoint, "您不在签到范围之内,距离打卡地点" + String.format("%.2f", mZuiJin) + "米", "#FF6C6C");
                                    showMessage("您不在签到范围之内,距离打卡地点" + String.format("%.2f", mZuiJin) + "米");
//                                    setMarkerOptions(LocationPoint, R.drawable.icon_ding_wei_red);
                                    setMarkerOptions(mDestinationPoint, R.drawable.restaurant_icon);
                                    commit_bt.setBackgroundDrawable(getResources().getDrawable(R.drawable.restaurant_btbg_gray));
                                    mBaiduMap.setMyLocationEnabled(true);
                                }
                                setMapZoomScale(LocationPoint);

                            }

                        }
                    } catch (JsonSyntaxException e) {
                        e.printStackTrace();
                    }

                }
            }


            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        });


    }

    //设置打卡目标范围圈
    private void setCircleOptions() {
        mBaiduMap.clear();
        if (mDestinationPoint == null) return;
        OverlayOptions ooCircle = new CircleOptions().fillColor(0x4057FFF8).center(mDestinationPoint).zIndex(2).stroke(new Stroke(1, 0xB6FFFFFF)).radius(DISTANCE);
        mBaiduMap.addOverlay(ooCircle);

    }

    /**
     * 添加地图文字
     *
     * @param point
     * @param str
     * @param color 字体颜色
     */
    private void setTextOption(LatLng point, String str, String color) {
        //使用MakerInfoWindow
        if (point == null) return;
        TextView view = new TextView(getApplicationContext());
        view.setBackgroundResource(R.drawable.map_textbg);
        view.setPadding(50, 23, 50, 0);
        view.setTypeface(Typeface.DEFAULT_BOLD);
        view.setTextSize(14);
        view.setGravity(Gravity.CENTER);
        view.setText(str);
        view.setTextColor(Color.parseColor(color));
        mInfoWindow = new InfoWindow(view, point, 170);
        mBaiduMap.showInfoWindow(mInfoWindow);
    }

    /**
     * 设置marker覆盖物
     *
     * @param ll   坐标
     * @param icon 图标
     */
    private void setMarkerOptions(LatLng ll, int icon) {
        if (ll == null) return;
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(icon);
        MarkerOptions ooD = new MarkerOptions().position(ll).icon(bitmap);
        mBaiduMap.addOverlay(ooD);
    }

    //改变地图缩放
    private void setMapZoomScale(LatLng ll) {
        if (mDestinationPoint == null) {
            mZoomScale = getZoomScale(ll);
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngZoom(ll, mZoomScale));//缩放
        } else {
            mZoomScale = getZoomScale(ll);
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngZoom(mCenterPos, mZoomScale));//缩放
        }
    }

    /**
     * 获取地图的中心点和缩放比例
     *
     * @return float
     */
    private float getZoomScale(LatLng LocationPoint) {
        double maxLong;    //最大经度
        double minLong;    //最小经度
        double maxLat;     //最大纬度
        double minLat;     //最小纬度
        List<Double> longItems = new ArrayList<Double>();    //经度集合
        List<Double> latItems = new ArrayList<Double>();     //纬度集合

        if (null != LocationPoint) {
            longItems.add(LocationPoint.longitude);
            latItems.add(LocationPoint.latitude);
        }
        if (null != mDestinationPoint) {
            longItems.add(mDestinationPoint.longitude);
            latItems.add(mDestinationPoint.latitude);
        }

        maxLong = longItems.get(0);    //最大经度
        minLong = longItems.get(0);    //最小经度
        maxLat = latItems.get(0);     //最大纬度
        minLat = latItems.get(0);     //最小纬度

        for (int i = 0; i < longItems.size(); i++) {
            maxLong = Math.max(maxLong, longItems.get(i));   //获取集合中的最大经度
            minLong = Math.min(minLong, longItems.get(i));   //获取集合中的最小经度
        }

        for (int i = 0; i < latItems.size(); i++) {
            maxLat = Math.max(maxLat, latItems.get(i));   //获取集合中的最大纬度
            minLat = Math.min(minLat, latItems.get(i));   //获取集合中的最小纬度
        }
        double latCenter = (maxLat + minLat) / 2;
        double longCenter = (maxLong + minLong) / 2;
        int jl = (int) getDistance(new LatLng(maxLat, maxLong), new LatLng(minLat, minLong));//缩放比例参数
        mCenterPos = new LatLng(latCenter, longCenter);   //获取中心点经纬度
        int[] zoomLevel = {2500000, 2000000, 1000000, 500000, 200000, 100000,
                50000, 25000, 20000, 10000, 5000, 2000, 1000, 500, 100, 50, 20, 0};
        int i;
        for (i = 0; i < 18; i++) {
            if (zoomLevel[i] < jl) {
                break;
            }
        }
        float zoom = i + 4;
        return zoom;
    }

    /**
     * 缩放比例参数
     *
     * @param var0
     * @param var1
     * @return
     */
    public double getDistance(LatLng var0, LatLng var1) {
        if (var0 != null && var1 != null) {
            Point var2 = CoordUtil.ll2point(var0);
            Point var3 = CoordUtil.ll2point(var1);
            return var2 != null && var3 != null ? CoordUtil.getDistance(var2, var3) : -1.0D;
        } else {
            return -1.0D;
        }
    }

    @OnClick(R.id.tv_qian_dao_ji_lu)
    void onQianDaoJiLu() {
        Utils.navigation(this, RouterHub.ACTIVITY_QIAN_DAO_JI_LU);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GPS_REQUEST_CODE) {
//            openGPSSEtting();
            client.restart();
        } else if (requestCode == 105) {
//            String bestImage0 = null;
//            if (data != null && !TextUtils.isEmpty(mSharedPreferencesHelper.getString("bestImage0"))) {
////                bestImage0 = data.getStringExtra("bestImage0");
//                bestImage0 = mSharedPreferencesHelper.getString("bestImage0");
//            }
////            String eye = data.getStringExtra("Eye");
//
//            if (!TextUtils.isEmpty(bestImage0)) {
//
//                try {
//                    Bitmap bitmap = ArmsUtils.base64ToBitmap(bestImage0);
//                    imgTouXiang.setImageBitmap(bitmap);
//
//                    imgStr = bestImage0;
//                    addAttence();
//                } catch (Exception e) {
//                    e.printStackTrace();
////                    showMessage("解析图片异常");
//                }
//            } else {
////                showMessage("签到失败,请重新签到。");
//            }
        } else {

//            PhotoUtil.onActivityResult(this, requestCode, resultCode, data);

        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mMapView != null) {

            mMapView.onResume();
        }
        if (mSensorManager != null) {

            //为系统的方向传感器注册监听器
            mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                    SensorManager.SENSOR_DELAY_UI);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);

        if (requestCode == 104) {
            SDKInitializer.initialize(getApplicationContext());//百度地图
            // 注册 SDK 广播监听者
            RegisterBroadcast();
        }
    }

    @Subscriber(tag = "bestImage0", mode = ThreadMode.MAIN)
    public void qianDao(String bestImage0) {
        if (!TextUtils.isEmpty(bestImage0)) {

            try {
                Bitmap bitmap = ArmsUtils.base64ToBitmap(bestImage0);
                imgTouXiang.setImageBitmap(bitmap);
                imgStr = bestImage0;
//                addAttence();
//                addAttence2();
                getAuth();
            } catch (Exception e) {
                e.printStackTrace();
//                    showMessage("解析图片异常");
            }
        } else {
//                showMessage("签到失败,请重新签到。");
        }
    }

    private void getAuth() {
        HashMap<String, String> map = new HashMap<>();
        mPresenter.getAuth(map);
    }

    /**
     * public int addAttence(string identityCardNo, string coordinate, string image)
     */
    @Deprecated
    private void addAttence() {

//        showLoading();

        String methodName = "addAttence";

        SoapUtil soapUtil = SoapUtil.getInstance(this);
        soapUtil.setDotNet(true);
        SoapParams params = new SoapParams();
        params.put("identityCardNo", mSharedPreferencesHelper.getString(BaseConstants.USERNAME));
        params.put("coordinate", mCurrentLon + "," + mCurrentLat);
        params.put("image", imgStr);
        params.put("city", mCity);


        /**
         * 请求
         */
        soapUtil.callEntry(BASE_URL, NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
//                hideLoading();

                String result = object.getProperty("addAttenceResult").toString();
//                if (result != null && !result.equals("-1")) {
//                    ArmsUtils.makeText(getContext(), "签到成功");
//                } else {
//                    ArmsUtils.makeText(getContext(), "签到失败");
//                }
                ArmsUtils.makeText(getContext(), result);
                mSharedPreferencesHelper.removeString("bestImage0");
//                mSharedPreferencesHelper.removeString("Eye");
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
//                ArmsUtils.makeText(getContext(), error.getMessage());
                ArmsUtils.makeText(getContext(), "打卡失败，请重新点击打卡。(访问接口失败)");
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
//                ArmsUtils.makeText(getContext(), fault.getMessage());
                ArmsUtils.makeText(getContext(), "打卡失败，请重新点击打卡。(访问接口失败)");
            }
        }, getAapiUserName(), getApiPwd());


    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        double x = sensorEvent.values[SensorManager.DATA_X];
        if (Math.abs(x - lastX) > 1.0) {
            mCurrentDirection = (int) x;
            locData = new MyLocationData.Builder()
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(mCurrentLat)
                    .longitude(mCurrentLon).build();
            mBaiduMap.setMyLocationData(locData);
        }
        lastX = x;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        ArmsUtils.makeText(this, "相关权限获取成功");
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        ArmsUtils.makeText(this, "请同意相关权限，否则功能无法使用");
    }

    @Override
    protected void onDestroy() {
        // 取消监听 SDK 广播
        unregisterReceiver(mReceiver);
        if (BDAblistener != null) {
            client.unRegisterLocationListener(BDAblistener);

        }
        if (client != null && client.isStarted()) {
            client.stop();
        }
        mMapView.onDestroy();
        mMapView = null;
        mHandler.removeCallbacks(run);
        super.onDestroy();

//        PhotoUtil.context = null;
    }

    @Override
    protected void onStop() {
        super.onStop();
        //取消注册传感器监听
        mSensorManager.unregisterListener(this);
    }

    private void getQianDaoData() {
        HashMap<String, String> map = new HashMap<>();

        mPresenter.getQianDaoData(map);
    }

    @Override
    public void getQianDaoDataSuccess(QianDao entityData) {


    }

    @Override
    public void getAuthSuccess(GetAuth entityData) {

        if (entityData != null && entityData.getAccess_token() != null) {
            try {

                String jsonData = "[\n" +
                        "    {\n" +
                        "        \"image\": \"" + imgStr + "\",\n" +
                        "        \"image_type\": \"BASE64\",\n" +
                        "         \"face_field\": \"age,beauty,spoofing\",\n" +
                        "         \"option\": \"COMMON\"\n" +
                        "    }\n" +
                        "]";
                RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonData);

                mPresenter.faceverify(entityData.getAccess_token(), body);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void faceverifySuccess(Faceverify entityData) {
        if (entityData != null && entityData.getResult() != null) {

            if (entityData.getResult().getFace_liveness() > 0.5) {
                addAttence2();
            } else {
                showMessage("请本人操作打卡，不要违规操作！！！");
            }
        }
    }

    private void addAttence2() {

        showLoading();

        String methodName = "addAttence2";

        SoapUtil soapUtil = SoapUtil.getInstance(this);
        soapUtil.setDotNet(true);
        SoapParams params = new SoapParams();
        params.put("identityCardNo", mSharedPreferencesHelper.getString(BaseConstants.USERNAME));
        params.put("image", imgStr);
        params.put("regionId", String.valueOf(mRegionId));


        /**
         * 请求
         */
        soapUtil.callEntry(BASE_URL, NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty("addAttence2Result").toString();
                ArmsUtils.makeText(getContext(), result);
                mSharedPreferencesHelper.removeString("bestImage0");
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
//                ArmsUtils.makeText(getContext(), error.getMessage());
                ArmsUtils.makeText(getContext(), "打卡失败，请重新点击打卡。(访问接口失败)");
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
//                ArmsUtils.makeText(getContext(), fault.getMessage());
                ArmsUtils.makeText(getContext(), "打卡失败，请重新点击打卡。(访问接口失败)");
            }
        }, getAapiUserName(), getApiPwd());


    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog(this);

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

//    private void shangChuanTouXiang() {
//        LinearLayout root = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.sales_client_bottom_dialog_pai_zhao, null);
//        Button btn_xiang_ce = root.findViewById(me.iwf.photopicker.R.id.btn_xiang_ce);
//        Button ben_xiang_ji = root.findViewById(me.iwf.photopicker.R.id.ben_xiang_ji);
//        Button btn_qu_xiao = root.findViewById(me.iwf.photopicker.R.id.btn_qu_xiao);
//        btn_qu_xiao.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (mBottomDialogUtilShare != null)
//                    mBottomDialogUtilShare.dismissDiaolog();
//            }
//        });
//        btn_xiang_ce.setVisibility(View.GONE);
//        btn_xiang_ce.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (mBottomDialogUtilShare != null)
//                    mBottomDialogUtilShare.dismissDiaolog();
//
//                PhotoUtil.begin()
//                        .setNeedCropWhenOne(false)
//                        .setNeedCompress(false)
//                        .setMaxSelectCount(1)
//
//                        .start(QianDaoActivity.this, 33, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
//                            @Override
//                            public void onFail(String msg, Throwable r, int requestCode) {
//                            }
//
//                            @Override
//                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
////
//                                try {
//                                    createMaterialForInstoreAuto(compressedPath);
//
//
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//                            }
//
//                            @Override
//                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
////                                refresh1(originalPaths);
//
//                            }
//
//                            @Override
//                            public void onCancel(int requestCode) {
//                            }
//                        }));
//            }
//        });
//        ben_xiang_ji.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (mBottomDialogUtilShare != null)
//                    mBottomDialogUtilShare.dismissDiaolog();
//                PhotoUtil.statusBarColor = R.color.public_black;
//                PhotoUtil.titleBarColor = R.color.public_black;
//                PhotoUtil.cropAvatar(true).setCropMuskOvalFalse()
//                        .start(QianDaoActivity.this, 23, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
//                            @Override
//                            public void onFail(String msg, Throwable r, int requestCode) {
//                            }
//
//                            @Override
//                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
//                                try {
//                                    createMaterialForInstoreAuto(compressedPath);
//
//
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//                            }
//
//                            @Override
//                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
//                            }
//
//                            @Override
//                            public void onCancel(int requestCode) {
//                            }
//                        }));
//            }
//        });
//
//        mBottomDialogUtilShare = new BottomDialogUtil(QianDaoActivity.this, root);
//        mBottomDialogUtilShare.showDiaolog();
//
//    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.arriver_bt) {

            if (getLocationPermission() && getPermission()) {


//                if (mDistance <= DISTANCE) {
//                    Toast.makeText(this, "打卡成功", Toast.LENGTH_SHORT).show();
//                } else {
//                    Toast.makeText(this, "外勤打卡", Toast.LENGTH_SHORT).show();
//                }

                if (isCanDaKa) {
                    startItemActivityForResult(FaceLivenessExpActivity.class);
                } else {
                    showMessage("您不在签到范围之内");
                }


//                if (imgStr.length() == 0) {
//                    shangChuanTouXiang();
//                } else {
//                    if (ArmsUtils.isNetworkAvailable(this)) {
////                        if (GpsUtil.checkGpsIsOpen(this)) {
//                        addAttence();
////                        }
//                    } else {
//                        ArmsUtils.makeText(this, "当前网络不可用");
//                        return;
//                    }
//                }
            }

        }
    }

    private boolean getPermission() {
        if (EasyPermissions.hasPermissions(this, permissions)) {
            return true;
        } else {
            EasyPermissions.requestPermissions(this, "需要获取您的相册、照相使用权限", 1, permissions);
            return false;
        }

    }

    private void startItemActivityForResult(Class itemClass) {
        setFaceConfig();
        startActivityForResult(new Intent(this, itemClass), 105);
    }

    private void createMaterialForInstoreAuto(String compressedPath) throws Exception {
        imgStr = ArmsUtils.bitmapPathToBase64String(compressedPath);
        Bitmap bitmap = BitmapFactory.decodeFile(compressedPath);
        imgTouXiang.setImageBitmap(bitmap);
//        HashMap<String, String> map = new HashMap<String, String>();
//        map.put("did", String.valueOf(did));
//        map.put("uid", mSharedPreferencesHelper.getString(BaseConstants.UID));
//        map.put("num", String.valueOf(num));
//        map.put("imgStr", String.valueOf(imgStr));
//
//        mPresenter.createMaterialForInstoreAuto(StorageActivity.this, map);
    }

    public class SDKReceiver extends BroadcastReceiver {

        public void onReceive(Context context, Intent intent) {
            String s = intent.getAction();
            String tx = "";

            if (s.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR)) {

                tx = "key 验证出错! 错误码 :" + intent.getIntExtra
                        (SDKInitializer.SDK_BROADTCAST_INTENT_EXTRA_INFO_KEY_ERROR_CODE, 0)
                        + " ; 请在 AndroidManifest.xml 文件中检查 key 设置";
            } else if (s.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK)) {
                tx = "key 验证成功! 功能可以正常使用";
            } else if (s.equals(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR)) {
                tx = "网 络出错";
            }
            if (tx.contains("错")) {
                AlertDialog.Builder normalDialog =
                        new AlertDialog.Builder(context);
                normalDialog.setTitle("提示");
                normalDialog.setMessage(tx);
                normalDialog.setPositiveButton("确定", null);
                normalDialog.setNegativeButton("关闭", null);
                // 显示
                normalDialog.show();
            } else {
//                Toast.makeText(context, tx, Toast.LENGTH_SHORT).show();
            }

        }
    }

}
